const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

const clients = [];
let leftFPSArr = {}
let righttFPSArr = {}

wss.on('connection', (ws) => {
  console.log('有新的客户端连接');
  leftFPSArr = {}
  righttFPSArr = {}
  clients.push(ws);

  ws.on('message', (messageBuffer) => {
    const messageString = messageBuffer.toString();
    let messageObject;
    // console.log(`收到的对象消息：`, messageString);

    try {
      messageObject = JSON.parse(messageString);
      if (messageObject?.messageType) {
        switch (messageObject?.messageType) {
          case 'fps':   //对比fps
            {
              const { type, mage, fps, value, randomName } = messageObject
              // let valueStr = `${type}__${fps}__${value}`
              let valueStr = `${type}__${randomName}__${fps}__${value}`
              if (mage == 'left') {
                if (!leftFPSArr[`${randomName}`]) {
                  leftFPSArr[`${randomName}`] = []
                }
                leftFPSArr[`${randomName}`].push(valueStr)
              } else {
                if (!righttFPSArr[`${randomName}`]) {
                  righttFPSArr[`${randomName}`] = []
                }
                righttFPSArr[`${randomName}`].push(valueStr)
              }
              dataComparison(leftFPSArr[`${randomName}`], righttFPSArr[`${randomName}`])
              break;
            }
          case 'monsterDie':   //dangqian 
            {
              const { mage, fps, monsterId } = messageObject
              // let valueStr = `${type}__${fps}__${value}`
              let valueStr = `${monsterId}__monsterDie__${fps}_${monsterId}`
              if (mage == 'left') {
                if (!leftFPSArr[`monsterDie`]) {
                  leftFPSArr[`monsterDie`] = []
                }
                leftFPSArr[`monsterDie`].push(valueStr)
                leftFPSArr.push(valueStr)
              } else {
                if (!righttFPSArr[`monsterDie`]) {
                  righttFPSArr[`monsterDie`] = []
                }
                righttFPSArr[`monsterDie`].push(valueStr)
              }
              dataComparison(leftFPSArr[`monsterDie`], righttFPSArr[`monsterDie`])
              break;
            }
          case 'bulletUpdateSelf':   //dangqian 
            {
              const { mage, fps, bulletId } = messageObject
              // let valueStr = `${type}__${fps}__${value}`
              let valueStr = `${bulletId}__bulletUpdateSelf__${fps}_${bulletId}`
              if (mage == 'left') {
                if (!leftFPSArr[`bulletUpdateSelf`]) {
                  leftFPSArr[`bulletUpdateSelf`] = []
                }
                leftFPSArr[`bulletUpdateSelf`].push(valueStr)
                leftFPSArr.push(valueStr)
              } else {
                if (!righttFPSArr[`bulletUpdateSelf`]) {
                  righttFPSArr[`bulletUpdateSelf`] = []
                }
                righttFPSArr[`bulletUpdateSelf`].push(valueStr)
              }
              dataComparison(leftFPSArr[`bulletUpdateSelf`], righttFPSArr[`bulletUpdateSelf`])
              break;
            }
          case 'bulletCol':   //dangqian 
            {
              const { mage, fps, bulletId } = messageObject
              // let valueStr = `${type}__${fps}__${value}`
              let valueStr = `${bulletId}__bulletCol__${fps}_${bulletId}`
              if (mage == 'left') {
                if (!leftFPSArr[`bulletCol`]) {
                  leftFPSArr[`bulletCol`] = []
                }
                leftFPSArr[`bulletCol`].push(valueStr)
                leftFPSArr.push(valueStr)
              } else {
                if (!righttFPSArr[`bulletCol`]) {
                  righttFPSArr[`bulletCol`] = []
                }
                righttFPSArr[`bulletCol`].push(valueStr)
              }
              dataComparison(leftFPSArr[`bulletCol`], righttFPSArr[`bulletCol`])
              break;
            }

            case 'bulletMove':   //dangqian 
            {
              const { mage, fps, bulletId } = messageObject
              // let valueStr = `${type}__${fps}__${value}`
              let valueStr = `${bulletId}__bulletMove__${fps}_${bulletId}`
              if (mage == 'left') {
                if (!leftFPSArr[`bulletMove`]) {
                  leftFPSArr[`bulletMove`] = []
                }
                leftFPSArr[`bulletMove`].push(valueStr)
                leftFPSArr.push(valueStr)
              } else {
                if (!righttFPSArr[`bulletMove`]) {
                  righttFPSArr[`bulletMove`] = []
                }
                righttFPSArr[`bulletMove`].push(valueStr)
              }
              dataComparison(leftFPSArr[`bulletMove`], righttFPSArr[`bulletMove`])
              break;
            }


          default:
            break;
        }
      } else {
        console.log("发送同步选牌信息", messageObject)
        broadcastMessage(messageString)
      }

    } catch (error) {
      // console.log(`无法将消息转换为对象：${error}`);
    }
  });

  ws.on('close', () => {
    console.log('客户端断开连接');
    // 从客户端列表中移除断开连接的客户端
    leftFPSArr = {}
    righttFPSArr = {}
    clients.splice(clients.indexOf(ws), 1);
  });

  ws.on('error', (error) => {
    console.log(`发生错误：${error}`);
  });
});

// 定义一个函数用于向所有客户端发送消息
function broadcastMessage(message) {
  clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(message);
    }
  });
}



//数据对比
function dataComparison(leftFPSArr, righttFPSArr) {
  const result = [];
  let leftIndex = 0;
  let rightIndex = 0;
  while (leftIndex < leftFPSArr.length && rightIndex < righttFPSArr.length) {
    let arrLeft = leftFPSArr[leftIndex].split("__")
    let arrRight = righttFPSArr[leftIndex].split("__")

    let dis = Math.abs(arrLeft[2] - arrRight[2])

    if (leftFPSArr[leftIndex] === righttFPSArr[rightIndex]) {
      result.push(true);
      console.log("对比正确", leftFPSArr[leftIndex], righttFPSArr[rightIndex])
      leftFPSArr.splice(leftIndex, 1);
      righttFPSArr.splice(rightIndex, 1);
    } else {
      result.push(false);
      console.log("发现错误的值", leftFPSArr[leftIndex], righttFPSArr[rightIndex])
      let message = {
        messageType: "pause"
      }
      broadcastMessage(JSON.stringify(message))
      leftIndex++;
      rightIndex++;
    }
  }

  return result;
}

console.log('WebSocket 服务器正在监听 8081 端口');